package com.ken.ability.auth.protocol.security;

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Security的client实体对象
 */
@Data
@Accessors(chain = true)
public class AuthClientDetails implements ClientDetails {

    //客户端id
    private Long id;
    //客户端名称
    private String clientId;
    //客户端密钥(加密)
    private String clientSecret;
    //授权Token的有效期
    private Integer accessTokenTime;
    //刷新Token的有效期
    private Integer refreshTokenTime;
    //设置该客户端的授权模式
    private String authGrantType;
    //重定向的url
    private String redirectUrl;
    //适用范围
    private String scope;

    /**
     * 返回应用的client_id
     * @return
     */
    @Override
    public String getClientId() {
        return clientId;
    }

    /**
     * 返回资源ids
     * @return
     */
    @Override
    public Set<String> getResourceIds() {
        return new HashSet<>();
    }

    /**
     * 是否需要client secret
     * @return
     */
    @Override
    public boolean isSecretRequired() {
        return true;
    }

    /**
     * 返回client_secret
     * @return
     */
    @Override
    public String getClientSecret() {
        return clientSecret;
    }

    @Override
    public boolean isScoped() {
        return true;
    }

    @Override
    public Set<String> getScope() {
        return Arrays.stream(scope.split(","))
                .collect(Collectors.toSet());
    }

    /**
     * 返回该client支持的oauth2授权方式
     * @return
     */
    @Override
    public Set<String> getAuthorizedGrantTypes() {
        return Arrays.stream(authGrantType.split(","))
                .collect(Collectors.toSet());
    }

    /**
     * 重定向的url
     * @return
     */
    @Override
    public Set<String> getRegisteredRedirectUri() {
        return Collections.singleton(redirectUrl);
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        return new ArrayList<>();
    }

    /**
     * 令牌的有效时间
     * @return
     */
    @Override
    public Integer getAccessTokenValiditySeconds() {
        return accessTokenTime;
    }

    /**
     * 刷新令牌的token的有效时间
     * @return
     */
    @Override
    public Integer getRefreshTokenValiditySeconds() {
        return refreshTokenTime;
    }

    /**
     * 是否能够自动通过
     * @param scope
     * @return
     */
    @Override
    public boolean isAutoApprove(String scope) {
        return true;
    }

    /**
     * 添加一些额外的信息
     * @return
     */
    @Override
    public Map<String, Object> getAdditionalInformation() {
        return null;
    }
}
